package com.example.recordingpen_datacollection.Utils.http;

import com.alibaba.fastjson.JSON;
import com.example.recordingpen_datacollection.Utils.AIUtil.pojo.aliyun.*;
import com.example.recordingpen_datacollection.Utils.AIUtil.pojo.aliyun.Messages;
import okhttp3.*;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.recordingpen_datacollection.Utils.http.HttpUrl.ALIYUNAIurlData;

public class AliYunHttpUtil {
    private static final String apiKey = "sk-fd35166024304acb9473aec3db52b059";

    public static AliYunJsonResult  getAliYunData(String role,String content) throws IOException {
        URL url = new URL(ALIYUNAIurlData);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(60*1000);
        connection.setReadTimeout(60*1000);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setDoOutput(true);
        AliYunJsonRoot aliYunJsonRoot = new AliYunJsonRoot();
        {
            Input input = new Input();
            {
                List<Messages> messagesList = new ArrayList<>();
                {
                    Messages systemRoleContent = Messages.createSystemRoleContent("你是一个会议总结助手");
                    Messages messages = new Messages();
                    messages.setRole(role);
                    messages.setContent(content);

                    messagesList.add(systemRoleContent);
                    messagesList.add(messages);
                }
                input.setMessages(messagesList);
            }

            Parameters parameters = new Parameters();
            parameters.setTop_p(0.4F);
            parameters.setTop_k(20);
            parameters.setTemperature(0.2F);
            parameters.setResult_format("message"); //\"result_format\": \"message\",
            aliYunJsonRoot.setModel("qwen-plus");
            aliYunJsonRoot.setInput(input);
            aliYunJsonRoot.setParameters(parameters);
        }


//        String jsonInputString = String.format("{\"model\": \"qwen-plus\", \"input\": {\"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, {\"role\": \"user\", \"content\": \"%s\"}]}, \"parameters\": {\"result_format\": \"message\"}}",UserInput);
        String jsonInputString = JSON.toJSONString(aliYunJsonRoot);

        /**
         * {
         * 	"model": "qwen-turbo",
         * 	"input": {
         * 		"messages": [{
         * 			"role": "system",
         * 			"content": "You are a helpful assistant."
         *                }, {
         * 			"role": "user",
         * 			"content": "1+1"
         *        }]* 	},
         * 	"parameters": {
         * 		"result_format": "message"
         * 	}
         * }
         */
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.write(jsonInputString.getBytes(StandardCharsets.UTF_8));
            wr.flush();
        }

        StringBuilder response = new StringBuilder();
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }

        /**
         *{
         * 	"output": {
         * 		"choices": [{
         * 			"finish_reason": "stop",
         * 			"message": {
         * 				"role": "assistant",
         * 				"content": "1 + 1 equals 2."
         *                        }* 		}]
         * 	},
         * 	"usage": {
         * 		"total_tokens": 30,
         * 		"output_tokens": 8,
         * 		"input_tokens": 22
         * 	},
         * 	"request_id": "45c1440a-b9a3-990c-9f7a-f9ecbfc3ff24"
         * }
         */
        connection.disconnect();
        AliYunJsonResult aliYunJsonResult = JSON.parseObject(response.toString(),AliYunJsonResult.class);
        return aliYunJsonResult;
    }

    public static String  getOKHttpAliYunData(String role,String content) throws IOException {
        String url = ALIYUNAIurlData;
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(120, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                .readTimeout(120, TimeUnit.SECONDS) // 设置读取超时时间为60秒
                .writeTimeout(120, TimeUnit.SECONDS) // 设置写入超时时间为60秒
                .build();

        AliYunJsonRoot aliYunJsonRoot = new AliYunJsonRoot();
        {
            Input input = new Input();
            {
                List<Messages> messagesList = new ArrayList<>();
                {
                    Messages systemRoleContent = Messages.createSystemRoleContent("你是一个会议总结助手");
                    Messages messages = new Messages();
                    messages.setRole(role);
                    messages.setContent(content);

                    messagesList.add(systemRoleContent);
                    messagesList.add(messages);
                }
                input.setMessages(messagesList);
            }

            Parameters parameters = new Parameters();
            parameters.setTop_p(0.8F);
            parameters.setTop_k(20);
            parameters.setTemperature(0.8F);
            parameters.setResult_format("message"); //\"result_format\": \"message\",
            aliYunJsonRoot.setModel("qwen-plus");
            aliYunJsonRoot.setInput(input);
            aliYunJsonRoot.setParameters(parameters);
        }


//        String jsonInputString = String.format("{\"model\": \"qwen-plus\", \"input\": {\"messages\": [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}, {\"role\": \"user\", \"content\": \"%s\"}]}, \"parameters\": {\"result_format\": \"message\"}}",UserInput);
        String jsonInputString = JSON.toJSONString(aliYunJsonRoot);

        RequestBody body = RequestBody.create(jsonInputString, MediaType.parse("application/json"));

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseData = response.body().string();
//                AliYunJsonResult aliYunJsonResult = JSON.parseObject(responseData,AliYunJsonResult.class);
                return responseData;
            } else {
                return "请求错误: "+response.code();
//                return response.message();
//                System.out.println("Request failed: " + ;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
